import { apiAuditUploadImage } from '../../other/api'

const { regeneratorRuntime, dayjs, uniq } = global

Page(global.connect(
  state => ({
    ...state.globalReducer,
    ...state.activityReducer
  }),
  dispatch => ({
    handleRoute: global.handleRoute,
    handleLicon1Tap(e) {
      console.log('handleLicon1Tap', e)
      wx.navigateBack()
    },
    async getUploadToken(data) {
      console.log('handleSubmit')
      const actionRes = await dispatch(global.globalReducer.getUploadToken(data))
      console.log(actionRes)
      if (actionRes.actionStatus !== 'SUCCESS') {
        this.selectComponent('#toast').handleShow({
          message: actionRes.apiMes
        })
      }
    },
    async handleGetAuditStoreList(e) {
      console.log('handleSubmit')
      const actionRes = await dispatch(global.activityReducer.getAuditStoreList({
        id: this.data.minaLoginRes.data.user_id,
      }))
      console.log(actionRes)
      if (actionRes.actionStatus !== 'SUCCESS') {
        this.selectComponent('#toast').handleShow({
          message: actionRes.apiMes
        })
      }
    },
    async handleSubmit(e) {
      try {

        console.log('handleSubmit')
        const {
          uiActivityStartTime,
          uiActivityEndTime,
          uiUpStartTime,
          uiUpEndTime,
          uiOrderEndTime,
          uiActivityName,
          uiLinks,
          uiFiles
        } = this.data

        console.log({
          uiActivityStartTime,
          uiActivityEndTime,
          uiUpStartTime,
          uiUpEndTime,
          uiOrderEndTime,
          uiActivityName,
          uiLinks,
          uiFiles
        })


        await this.getUploadToken({ num: uiLinks.length })
        const { token, domain, upDomain } = this.data.uploadTokenRes.data
        const task = []
        let allStores = []
        uiLinks.map((item, index) => task.push(
          new Promise((resolve, reject) => {
            const form = {
              url: upDomain,
              filePath: item.uiTempFiles.tempFilePaths[0],
              name: 'file',
              formData: {
                key: Array.isArray(token) ? token[index].key : token.key,
                token: Array.isArray(token) ? token[index].token : token.token
              }
            }
            console.log(form)
            // step1 把图片传到七牛
            wx.uploadFile({
              ...form,
              success(res) {
                // step2 把效果图与门店关系保存到数据库
                allStores = allStores.concat(item.uiStores)
                console.log(res)
                const parseRes = JSON.parse(res.data)
                apiAuditUploadImage({
                  image_name: item.uiImageName,
                  image_url: `${domain}/${parseRes.key}`,
                  store_ids: item.uiStores.map(i => i.id).join(','),
                }).then(res => {
                  resolve(res)
                }).catch(res => {
                  reject(res)
                })
              },
              fail(res) {
                reject(res)
              }
            })
          })
        ))

        const upLoadRes = await Promise.all(task)
        console.log(upLoadRes)

        const actionRes = await dispatch(global.activityReducer.createActivity({
          ...e.detail.value,
          audit_user_id: this.data.minaLoginRes.data.user_id,
          activity_start_time: Number(dayjs(uiActivityStartTime).valueOf().toString().substring(0, 10)),
          activity_end_time: Number(dayjs(uiActivityEndTime).valueOf().toString().substring(0, 10)),
          up_start_time: Number(dayjs(uiUpStartTime).valueOf().toString().substring(0, 10)),
          up_end_time: Number(dayjs(uiUpEndTime).valueOf().toString().substring(0, 10)),
          order_end_time: Number(dayjs(uiOrderEndTime).valueOf().toString().substring(0, 10)),
          store_ids: uniq(allStores.map(i => i.id)).join(','),
          img_ids: upLoadRes.map(i => i.data.id),
        }))
        console.log(actionRes)
        if (actionRes.actionStatus === 'SUCCESS') {
          this.selectComponent('#toast').handleShow({
            type: 'success',
            message: actionRes.apiMes
          })
          wx.navigateBack()
        } else {
          this.selectComponent('#toast').handleShow({
            message: actionRes.apiMes
          })
        }
      } catch (error) {
        console.error(error)
        this.selectComponent('#toast').handleShow({ message: error })
      }
    }
  })
)({
  data: {
    uiStores: [
    ],
    uiCheckedLength: 0,
    uiCheckedStores: [
    ],
    uiTempLink: {
      uiTempFiles: {
        tempFilePaths: [],
        tempFiles: []
      },
      uiStores: [],
      uiImageName: '',
    },
    uiLinks: [
    ],
    uiTempFiles: {
      tempFilePaths: [],
      tempFiles: []
    },
    uiTempImageName: '',
    uiFiles: {
      tempFilePaths: [],
      tempFiles: []
    },

    uiActivityName: '',
    uiActivityStartTime: '',
    uiActivityEndTime: '',
    uiUpStartTime: '',
    uiUpEndTime: '',
    uiOrderEndTime: ''
  },
  onLoad(options) {
    console.log('create-activity onLoad')
    this.handleGetAuditStoreList()
  },
  handleCalendar(e) {
    const { title, range } = e.currentTarget.dataset
    const {
      uiActivityStartTime,
      uiActivityEndTime,
      uiUpStartTime,
      uiUpEndTime,
      uiOrderEndTime
    } = this.data
    switch (title) {
      case '活动时间':
        {
          this.selectComponent('#dialog1').handleShow(null, {
            title, range,
            startDate: uiActivityStartTime,
            endDate: uiActivityEndTime,
          })
          break;
        }
      case '上画时间':
        {
          this.selectComponent('#dialog1').handleShow(null, {
            title, range,
            parts: [],
            startDate: uiUpStartTime,
            endDate: uiUpEndTime
          })
          break;
        }
      case '下单截止时间':
        {
          this.selectComponent('#dialog1').handleShow(null, {
            title, range,
            parts: [],
            startDate: uiOrderEndTime,
          })
          break;
        }
      default:
        break;
    }
  },
  handleChooseImage(e) {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success(res) {
        const { uiTempLink } = that.data
        const { tempFilePaths, tempFiles } = res
        uiTempLink.uiTempFiles = { tempFilePaths, tempFiles }
        that.setData({
          uiTempLink
        })
      },
      fail(res) {
        console.error(res)
      }
    })
  },
  handleSetUiTempLink(uiTempLink) {
    this.setData({
      uiTempLink: uiTempLink || {
        uiTempFiles: {
          tempFilePaths: [],
          tempFiles: []
        },
        uiStores: [],
        uiImageName: ''
      }
    })
  },
  handleSetUiTempFile(uiTempFile) {
    this.setData({
      uiTempFiles: uiTempFile || {
        tempFilePaths: [],
        tempFiles: []
      },
    })
  },
  // 统一的打开方式
  handleShowDialog(e, selector) {
    selector = selector || (e && e.currentTarget.dataset.selector)
    console.log('handleShowDialog', selector)
    switch (selector) {
      case 'dialog2':
        {
          const copy = JSON.parse(JSON.stringify(this.data.auditStoreList.data))
          console.log(copy)
          this.selectComponent('#' + selector).handleShow(null, copy)
          break;
        }
      // 打开选择效果图框
      case 'dialog3':
        {
          this.handleSetUiTempLink()
          this.selectComponent('#' + selector).handleShow(null, null)
          break;
        }
      // 打开“参与门店”选择框
      case 'dialog4':
        {
          const copy = JSON.parse(JSON.stringify(this.data.auditStoreList.data))
          const oriStores = copy.filter(i => i.checked).map(i => ({
            ...i,
            checked: true,
            show: true
          }))
          this.selectComponent('#' + selector).handleShow(null, oriStores)
          break;
        }
      default:
        break;
    }
  },
  // 统一的关闭方式（遮罩关闭，按钮关闭）
  handleHideDialog(e, selector, data) {
    selector = selector || (e && e.currentTarget.dataset.selector)
    console.log('handleHideDialog', selector)
    switch (selector) {
      case 'dialog3':
        {
          this.handleSetUiTempLink()
          this.handleSetUiTempFile()
          break;
        }
      default:
        break;
    }
  },
  // 统一的确认按钮
  handleConfirmDialog(e, selector) {
    selector = selector || (e && e.currentTarget.dataset.selector)
    console.log('handleConfirmDialog', selector)
    switch (selector) {
      case 'dialog1':
        {
          const { data, cb } = e.detail
          cb && cb()
          switch (data.title) {
            case '活动时间':
              {
                this.setData({
                  uiActivityStartTime: data.startDate,
                  uiActivityEndTime: data.endDate
                })
                break;
              }
            case '上画时间':
              {
                let ed = ''
                if (data.startDate) {
                  this.setData({
                    uiOrderEndTime: dayjs(data.startDate).subtract(1, 'days').format('YYYY-MM-DD')
                  })
                }
                this.setData({
                  uiUpStartTime: data.startDate,
                  uiUpEndTime: data.endDate,
                })
                break;
              }
            case '下单截止时间':
              {
                this.setData({
                  uiOrderEndTime: data.startDate
                })
                break;
              }
            default:
              break;
          }
          break;
        }
      case 'dialog2':
        {
          const { data, cb } = e.detail
          const { auditStoreList } = this.data
          auditStoreList.data = data
          this.setData({
            uiStores: data,
            auditStoreList,
            uiCheckedLength: data.filter(i => i.checked).length
          })
          cb && cb()

          this.handleSetUiTempLink()
          break;
        }
      case 'dialog3':
        {
          const { uiTempLink, uiLinks, uiFiles } = this.data
          // 校验
          let flag = true
          if (!uiTempLink.uiTempFiles.tempFilePaths.length) {
            flag = false
          }
          if (!uiTempLink.uiImageName.trim()) {
            flag = false
          }
          if (!uiTempLink.uiStores.length) {
            flag = false
          }
          if (!flag) {
            this.selectComponent('#toast').handleShow({
              message: '请完善效果图相关信息'
            })
            return
          }

          uiLinks.push(JSON.parse(JSON.stringify(uiTempLink)))

          uiFiles.tempFilePaths = uiFiles.tempFilePaths.concat(uiTempLink.uiTempFiles.tempFilePaths)
          uiFiles.tempFiles = uiFiles.tempFiles.concat(uiTempLink.uiTempFiles.tempFiles)

          this.setData({ uiTempLink, uiFiles, uiLinks })
          this.selectComponent('#' + selector).handleHide()
          break;
        }
      case 'dialog4':
        {
          const { uiTempLink } = this.data
          const { data, cb } = e.detail


          console.log(data)
          uiTempLink.uiStores = data.filter(i => i.checked)
          this.setData({
            uiTempLink
          })
          cb && cb()
          // this.selectComponent('#dialog4').handleHide()
          // this.selectComponent('#dialog5').handleShow(null, null)
          break;
        }
      case 'dialog5':
        {
          this.selectComponent('#dialog5').handleHide()
        }
      default:
        break;
    }
  },
  // 统一的取消按钮
  handleHideDialog(e, selector) {
    selector = selector || (e && e.currentTarget.dataset.selector)
    console.log('handleCancelDialog', selector)
    switch (selector) {
      case 'dialog3':
        {
          break;
        }
      case 'dialog4':
        {
          break;
        }
      case 'dialog5':
        {
          this.handleSetUiTempLink()
        }
        break;
      default:
        break;
    }
  },
  handleImageNameInput(e) {
    const { uiTempLink } = this.data
    uiTempLink.uiImageName = e.detail.value
    this.setData({ uiTempLink })
  },
  handleActivityNameInput(e) {
    this.setData({ uiActivityName: e.detail.value })
  },
  handleDeleteLink(e) {
    const { uiLinks } = this.data
    const { index } = e.currentTarget.dataset
    uiLinks.splice(index, 1)
    this.setData({ uiLinks })
  }
}))
